package com.gl.glcourses.mail.impl;

import java.util.ArrayList;
import java.util.Map;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;

import com.gl.glcourses.mail.Sender;
import com.gl.glcourses.vos.Usuario;
import com.gl.glcourses.vos.constants.Constants;

@Component
public abstract class VelocityEmailSender implements Sender {

	protected final VelocityEngine velocityEngine;
	protected final JavaMailSender mailSender;
	@Autowired
    protected TaskExecutor taskExecutor;
	@Autowired
	protected String appUrl;

    protected class SendTask implements Runnable {

      private MimeMessagePreparator preparator;

      public SendTask(MimeMessagePreparator preparator) {
        this.preparator = preparator;
      }

      public void run() {
    	  mailSender.send(preparator);
      }

    }

    @Autowired
    public VelocityEmailSender(VelocityEngine velocityEngine, JavaMailSender mailSender) {
    	this.velocityEngine = velocityEngine;
    	this.mailSender = mailSender;	
    }

    protected String getFrom()
    { 
    	return "bibliotecagloballogic@gmail.com";
    }
    
    protected String[] getTo( final Map<Object, Object> hTemplateVariables )
    {
		ArrayList<Usuario>lista = (ArrayList<Usuario>) hTemplateVariables.get(Constants.USUARIOS);
		String[] to = new String[ lista.size() ];
        int toInx = 0;
	    for (Usuario usuario : lista) {
	  	  to[ toInx ] = usuario.getMail();
	  	  toInx++;
	    }
	    hTemplateVariables.remove(Constants.USUARIOS);
	    return to;
    }
    
    protected String getToUsuario( final Map<Object, Object> hTemplateVariables )
    {
		Usuario usuario = (Usuario) hTemplateVariables.get(Constants.USUARIO_PM);
	    hTemplateVariables.remove(Constants.USUARIO_PM);
	    return usuario.getMail();
    }

    protected void execute(MimeMessagePreparator preparator) {
		taskExecutor.execute( new SendTask(preparator) );
    }
    
}
